package simulator;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JSplitPane;
import java.awt.Dimension;
import javax.swing.JScrollPane;
import java.awt.SystemColor;
import java.awt.Component;
import javax.swing.JButton;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTabbedPane;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.awt.FlowLayout;

public class InterfaceFrame extends JFrame {

	Dimension dimension;
	protected Color colorDarkS = new Color(0,0,80);
    protected Color colorDarkL = new Color(128, 0, 0);
    protected Color colorLightS = new Color(0,0,255);
    protected Color colorLightL = new Color(204, 119, 34);
    
    protected Image img_incinerator = Toolkit.getDefaultToolkit().getImage("img/incinerator.png");
    protected Image img_pano_vassoura = Toolkit.getDefaultToolkit().getImage("img/pano_vassoura.png");
    protected Image img_solvente_compatimento = Toolkit.getDefaultToolkit().getImage("img/solvente_compatimento.png");

    protected String namesRobs[]= {"RobSmall0","RobSmall1", "RobSmall2", "RobBig"};

    int time_incinerator=0;
    int escale_resize;
    JPanel panel_1;
    JSplitPane splitPane_left;
    private JButton btnAddGarbage;
    static FildGrid fildgrid;
    private JTabbedPane tabbedPane;
    static XYSeries series0 = new XYSeries("Number of type '0' garbages");
    static XYSeries series1 = new XYSeries("Number of type '1' garbages");
    static XYSeries series2 = new XYSeries("Robs incoalition");
    
    private JTextField tf_total_robs;
    private JTextField tf_current_number_garbages;
    private JLabel lb_countdown_incinerator;
    private JProgressBar progressBar_incinerator;
	private int maxIncinerator=5;
	private JMenuBar menuBar;
	private static DefaultPieDataset datasetPie[];
	private static JTable table;

	public InterfaceFrame(FildGrid _fildgrid) {
		this.fildgrid=_fildgrid;
		this.dimension=new Dimension(fildgrid.escale*fildgrid.gridSize,fildgrid.escale*fildgrid.gridSize);	
		this.escale_resize=fildgrid.escale;
    	setSize(new Dimension(800, 600));
    	datasetPie = new DefaultPieDataset[fildgrid.numberOfRobs];
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setTitle(" -- Enviroment -- ");
		
		JSplitPane splitPane_main = new JSplitPane();
		splitPane_main.setAutoscrolls(true);
		splitPane_main.setBackground(SystemColor.menu);
		splitPane_main.setPreferredSize(new Dimension(600, 700));
		getContentPane().add(splitPane_main);
		
		tabbedPane = new JTabbedPane();		
		tabbedPane.setBackground(Color.LIGHT_GRAY);
		
		//gr�ficos XY
		tabbedPane.addTab("Graphics", this.createGraphic("Data in ticks"," Ticks",""));
		splitPane_main.setRightComponent(tabbedPane);
		
		//gr�ficos Pie
		JPanel panelPies =new JPanel();
		panelPies.setLayout(new GridLayout((int) Math.floor(Math.sqrt(fildgrid.numberOfRobs)),(int) Math.ceil(Math.sqrt(fildgrid.numberOfRobs))));
		//panelPies.setLayout(new GridLayout(2,2));
		for(int i=0;i<fildgrid.numberOfRobs;i++){
			datasetPie[i] = new DefaultPieDataset();
			double used=0;
			if(fildgrid.totalCoallition!=0){
				used = (((double)(fildgrid.pos[i][2]))/((double)(fildgrid.totalCoallition)))*100.0;
			}
		 	double notUsed = 100-used;
			datasetPie[i].setValue("Used", used);
		 	datasetPie[i].setValue("Not used",notUsed);
		 	panelPies.add(createPieChart(this.datasetPie[i], this.namesRobs[i]));
		}
		tabbedPane.addTab("Pie Charts", panelPies);
	
        
        table = new JTable(new Object[][] {
        		{null, null, null},
        		{null, null, null},
        		{null, null, null},
        	}, new String[] {"Rob", "Bid", "Winner"});     
        JScrollPane scrollPane = new JScrollPane(table);
        tabbedPane.addTab("Auction Details", scrollPane);
	
		
		splitPane_left = new JSplitPane();
		splitPane_left.setPreferredSize(new Dimension(200, 200));
		splitPane_left.setOrientation(JSplitPane.VERTICAL_SPLIT);
		splitPane_main.setLeftComponent(splitPane_left);
		
		//JPanel 2
		JPanel panel_2 = new JPanel();
		panel_2.setBackground(Color.LIGHT_GRAY);
		panel_2.setForeground(Color.BLACK);
		splitPane_left.setRightComponent(panel_2);
		
		btnAddGarbage = new JButton("Create garbage");
		btnAddGarbage.setMinimumSize(new Dimension(10, 10));
		btnAddGarbage.setAlignmentX(Component.CENTER_ALIGNMENT);
		btnAddGarbage.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				fildgrid.createGarbage();
			}
		});
		
		tf_total_robs = new JTextField();
		tf_total_robs.setEditable(false);
		tf_total_robs.setColumns(10);
		
		JLabel lb_add_garbage = new JLabel("Add garbage");
		
		JLabel lb_number_robs = new JLabel("Total n\u00BA of Robs:");
		
		tf_current_number_garbages = new JTextField();
		tf_current_number_garbages.setEditable(false);
		tf_current_number_garbages.setColumns(10);
		
		JLabel lb_current_number_garbages = new JLabel("current n\u00BA of garbages:");
		
		lb_countdown_incinerator = new JLabel("Loading incinerator("+this.maxIncinerator+"):");
		
		progressBar_incinerator = new JProgressBar();
		progressBar_incinerator.setMaximum(maxIncinerator);
		
		GroupLayout gl_panel_2 = new GroupLayout(panel_2);
		gl_panel_2.setHorizontalGroup(
			gl_panel_2.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel_2.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_panel_2.createParallelGroup(Alignment.LEADING)
						.addComponent(lb_number_robs)
						.addComponent(lb_add_garbage)
						.addComponent(lb_current_number_garbages)
						.addComponent(lb_countdown_incinerator))
					.addGap(80)
					.addGroup(gl_panel_2.createParallelGroup(Alignment.LEADING)
						.addComponent(btnAddGarbage, Alignment.TRAILING, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(progressBar_incinerator, 0, 0, Short.MAX_VALUE)
						.addGroup(Alignment.TRAILING, gl_panel_2.createParallelGroup(Alignment.LEADING, false)
							.addComponent(tf_current_number_garbages, Alignment.TRAILING)
							.addComponent(tf_total_robs, Alignment.TRAILING)))
					.addContainerGap())
		);
		gl_panel_2.setVerticalGroup(
			gl_panel_2.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_2.createSequentialGroup()
					.addGroup(gl_panel_2.createParallelGroup(Alignment.BASELINE)
						.addComponent(lb_add_garbage)
						.addComponent(btnAddGarbage, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_panel_2.createParallelGroup(Alignment.BASELINE)
						.addComponent(lb_number_robs)
						.addComponent(tf_total_robs, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGap(12)
					.addGroup(gl_panel_2.createParallelGroup(Alignment.BASELINE)
						.addComponent(lb_current_number_garbages)
						.addComponent(tf_current_number_garbages, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGap(18)
					.addGroup(gl_panel_2.createParallelGroup(Alignment.LEADING)
						.addComponent(lb_countdown_incinerator)
						.addComponent(progressBar_incinerator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(314, Short.MAX_VALUE))
		);
		panel_2.setLayout(gl_panel_2);
		
		//JPanel 1
		panel_1 = new JPanel();
		panel_1.setMinimumSize(new Dimension(100, 100));
		panel_1.setPreferredSize(new Dimension(300, 200));
		panel_1.setBackground(Color.DARK_GRAY);
		panel_1.setSize(dimension);
		splitPane_left.setLeftComponent(panel_1);
	
		GridPanel gridpanel = new GridPanel();
		gridpanel.setSize(this.dimension=new Dimension(fildgrid.escale*fildgrid.gridSize,fildgrid.escale*fildgrid.gridSize));
		
		panel_1.add(gridpanel);
		panel_1.setLayout(null);
		
		menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		JMenu aboutMenu = new JMenu("About");
		menuBar.add(aboutMenu);
		
		JMenuItem problemMenuItem = new JMenuItem("Problem");
		aboutMenu.add(problemMenuItem);
		
		JMenuItem teamMenuItem = new JMenuItem("Team");
		aboutMenu.add(teamMenuItem);
	
	}
	public static void addSeries0(int _x, int _y) {
		series0.add(_x, _y);
	}
	public static void addSeries1(int _x, int _y) {
		series1.add(_x, _y);
	}
	public static void addSeries2(int _x, int _y) {
		series2.add(_x, _y);
	}
	public static void addUpdateDatasetPies(){
		for(int i=0;i<fildgrid.numberOfRobs;i++){
			double used=0;
			if(fildgrid.totalCoallition!=0){
				used = (((double)(fildgrid.pos[i][2]))/((double)(fildgrid.totalCoallition)))*100.0;
			}
		 	double notUsed = 100-used;
			datasetPie[i].setValue("Used", used);
		 	datasetPie[i].setValue("Not used",notUsed);
		}
	}
	
	public void putGarbageIncinerator(int n){
		if((progressBar_incinerator.getValue()+n)>maxIncinerator){		
			progressBar_incinerator.setValue(0);
		}else{
			progressBar_incinerator.setValue(progressBar_incinerator.getValue()+n);
		}
	}

    public ChartPanel createGraphic(String title, String x_vertice, String y_vertice) {
    	XYSeriesCollection dataset = new XYSeriesCollection();
	    dataset.addSeries(series0);
	    dataset.addSeries(series1);
        JFreeChart chart = ChartFactory.createXYLineChart(
            title,
            x_vertice,
            y_vertice,
            dataset,
            PlotOrientation.VERTICAL,
            true,
            false,
            false
        );
        XYPlot plot = (XYPlot) chart.getPlot();
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setSeriesLinesVisible(0, true);
        renderer.setSeriesShapesVisible(0, false);
        renderer.setSeriesPaint(0, colorDarkS);
        renderer.setSeriesLinesVisible(1, true);
        renderer.setSeriesShapesVisible(1, false);
        renderer.setSeriesPaint(0, colorDarkL);
        renderer.setSeriesLinesVisible(2, true);
        renderer.setSeriesShapesVisible(2, false);
        renderer.setSeriesPaint(0, Color.green);

        plot.setRenderer(renderer);
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setAlignmentY(Component.TOP_ALIGNMENT);
        chartPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        //chartPanel.setPreferredSize(new Dimension(0, 0));
        //chartPanel.setLayout(new BorderLayout(0, 0));
		return chartPanel;    
	}
    private static ChartPanel createPieChart(DefaultPieDataset dataset, String title) {	 	
        JFreeChart chart = ChartFactory.createPieChart(
            title,  // chart title
            dataset,             // data
            true,               // include legend
            true,
            false
        );

        PiePlot plot = (PiePlot) chart.getPlot();
        //plot.setSimpleLabels(true);
        
        plot.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
        plot.setNoDataMessage("No data available");
        plot.setCircular(false);
        plot.setLabelGap(0.02);
                
        ChartPanel chartPanel = new ChartPanel(chart);
        return chartPanel;
        
    }
    public static void setValueAtTable(String st, int row, int column){
    	table.setValueAt(st, row, column);
    }
    public static void resetValuesTable(){
    	for(int row=0;row<fildgrid.numberOfRobs-1;row++){
    		table.setValueAt("", row, 0);
    		table.setValueAt("", row, 1);
    		table.setValueAt("", row, 2);
    	}
    }
    public static void setValueAtTableWinner(){
    	for(int row=0;row<fildgrid.numberOfRobs-1;row++){
    		table.setValueAt("", row, 2);
    	}
    }
	
	class GridPanel extends JPanel{

        public GridPanel(){
        	        	        	
        }
        @Override
        public void paintComponent(Graphics g) {
        	tf_current_number_garbages.setText(fildgrid.garbages.size()+"");
        	tf_total_robs.setText(fildgrid.numberOfRobs+"");
        	if(panel_1.getHeight()>panel_1.getWidth()){
        		escale_resize=(int)(panel_1.getWidth()/fildgrid.gridSize);
        	}else{
        		escale_resize=(int)(panel_1.getHeight()/fildgrid.gridSize);
        	}
        	setSize(splitPane_left.getSize());
        	
            super.paintComponent(g);    
               g.setColor(Color.WHITE);
               Dimension size = getSize();
               g.fillRect(0, 0, size.width, size.height);
               
               g.setColor(Color.BLACK);
               
               for(int i=0;i<fildgrid.gridSize+1;i++){
            	   g.drawLine(i*escale_resize,0, i*escale_resize, escale_resize*fildgrid.gridSize);//linhas verticais
            	   g.drawLine(0,i*escale_resize,escale_resize*fildgrid.gridSize,i*escale_resize);//linhas horizaontais
               }
               int temp_escale_resize=(int)escale_resize/2;
               int temp_escale_resize2=((int)(escale_resize*(1.2))-temp_escale_resize)/(fildgrid.numberOfRobs);
               
               //garbages
               for(int i=0;i<fildgrid.garbages.size();i++){
            	   if(fildgrid.garbages.get(i).getSweeped()==false){
            		   switch(fildgrid.garbages.get(i).getType()){
                	   case(0):g.setColor(colorDarkS);
                		   break;
                	   case(1):g.setColor(colorDarkL);
                		   break;
                	   }
            	   }
            	   else{
            		   switch(fildgrid.garbages.get(i).getType()){
                	   case(0):g.setColor(colorLightS);
                		   break;
                	   case(1):g.setColor(colorLightL);
                		   break;
                	   }
            	   }
            	   
            	   g.fillRect(escale_resize*fildgrid.garbages.get(i).getX()+1, escale_resize*fildgrid.garbages.get(i).getY(), escale_resize, escale_resize);
               }
               g.setColor(Color.BLACK);
               //robots
               for(int i=0;i<fildgrid.numberOfRobs;i++){
            	   int px=escale_resize*fildgrid.pos[i][0]+1;
      			   int py=escale_resize*fildgrid.pos[i][1]+1;
      			   int lx=escale_resize*(fildgrid.gridSize)+1;
      			   int ly=escale_resize*i+1;
      			   int temp_escale_resize_image=escale_resize-2;
            	   switch(i){
            	   case 0: //g.setColor(Color.GREEN);
            	   			g.drawImage(img_pano_vassoura, px, py, temp_escale_resize_image, temp_escale_resize_image, this);
            	   			//g.drawImage(img_vassoura, lx, ly, temp_escale_resize_image, temp_escale_resize_image, this);
            	   		break;
            	   case 3: //g.setColor(Color.YELLOW);
            	   			g.drawImage(img_solvente_compatimento, px, py, temp_escale_resize_image, temp_escale_resize_image, this);
            	   			//g.drawImage(img_pano, lx, ly, temp_escale_resize_image, temp_escale_resize_image, this);
            	   			break;
            	   case 1: //g.setColor(Color.RED);
            	   			g.drawImage(img_pano_vassoura, px, py, temp_escale_resize_image, temp_escale_resize_image, this);
            	   			//g.drawImage(img_vagao, lx, ly, temp_escale_resize_image, temp_escale_resize_image, this);
            	   			break;
            	   case 2: //g.setColor(Color.ORANGE);
          	   				g.drawImage(img_pano_vassoura, px, py, temp_escale_resize_image, temp_escale_resize_image, this);
          	   				//g.drawImage(img_pano, lx, ly, temp_escale_resize_image, temp_escale_resize_image, this);
          	   			break;
            	   }
            	   //g.fillOval(escale_resize*pos[i][0]+temp_escale_resize2*i, escale_resize*pos[i][1]+temp_escale_resize2*i, temp_escale_resize, temp_escale_resize);
            	   //legendas robos
            	   //g.fillOval(escale_resize*gridSize+5,escale_resize*i,temp_escale_resize,temp_escale_resize);
            	   //g.drawString(namesRobs[i],escale_resize*(gridSize+1),escale_resize*(i+1)-(int)(escale_resize/2));
            	   
            	  
               }
               //legendas lixos
               /*
        	   g.setColor(colorDarkS);
        	   g.fillRect(escale_resize*gridSize+5, escale_resize*numberOfRobs, temp_escale_resize, temp_escale_resize);
        	   g.drawString("s�lido",escale_resize*gridSize+5, escale_resize*(numberOfRobs)+(int)(escale_resize/1.25));
        	   
        	   g.setColor(colorDarkL);
        	   g.fillRect(escale_resize*gridSize+5, escale_resize*(numberOfRobs+1), temp_escale_resize, temp_escale_resize);
        	   g.drawString("liquido",escale_resize*gridSize+5, escale_resize*(numberOfRobs+1)+(int)(escale_resize/1.25));
     
        	   g.setColor(colorLightS);
        	   g.fillRect(escale_resize*gridSize+5, escale_resize*(numberOfRobs+2), temp_escale_resize, temp_escale_resize);
        	   g.drawString("solido-varrido",escale_resize*gridSize+5, escale_resize*(numberOfRobs+2)+(int)(escale_resize/1.25));       	   
        	   
        	   g.setColor(colorLightL);
        	   g.fillRect(escale_resize*gridSize+5, escale_resize*(numberOfRobs+3), temp_escale_resize, temp_escale_resize);
        	   g.drawString("liquido-passado pano",escale_resize*gridSize+5, escale_resize*(numberOfRobs+3)+(int)(escale_resize/1.25));
        	   */
        	   g.setColor(Color.BLACK);
        	   g.drawImage(img_incinerator, escale_resize*fildgrid.gridSize, escale_resize*(fildgrid.gridSize-1), escale_resize, escale_resize,this);
        	   g.drawString("incinerador", escale_resize*fildgrid.gridSize+5, escale_resize*(fildgrid.gridSize-1));
                            
        }
    }
}
